package com.iuie.ns.system.shiro.realm;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.iuie.ns.frame.utils.ListUtils;
import com.iuie.ns.system.service.user.ISysUserService;
import com.iuie.ns.system.vo.user.SysUserVO;

public class MyShiroRealm extends AuthorizingRealm {
	
	@Autowired
	private ISysUserService userService;

	// 授权，查询用户的权限，赋予用户权限
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
	    // 角色 / 权限
	    SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        String userId = (String)principals.getPrimaryPrincipal();
        // 查询用户角色
        authorizationInfo.setRoles(ListUtils.toHashSet(userService.findRoleCodesByUserId(userId)));
        authorizationInfo.setStringPermissions(ListUtils.toHashSet(userService.findPermissionCodesByUserId(userId)));
        return authorizationInfo;
	}

	// 身份验证
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
	    String userId = (String) authcToken.getPrincipal();
	    
	    SysUserVO user = userService.findById(userId);
	    
	    if(user.getUserState() != null && user.getUserState() == 0){
            throw new LockedAccountException();
        }
	    SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user.getUserId(), user.getUserPwd(), getName());
        this.clearCache(authenticationInfo.getPrincipals());//清除
		return authenticationInfo;
	}
	
	public void clearAllCachedAuthorizationInfo() {
        getAuthorizationCache().clear();
    }

    public void clearAllCachedAuthenticationInfo() {
        getAuthenticationCache().clear();
    }

    public void clearAllCache() {
        clearAllCachedAuthenticationInfo();
        clearAllCachedAuthorizationInfo();
    }
    
    @Override
    public void clearCachedAuthorizationInfo(PrincipalCollection principals) {
        super.clearCachedAuthorizationInfo(principals);
    }
    
    

}
